<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>调查问卷</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
        }

        h1 {
            color: #667eea;
            text-align: center;
            margin-bottom: 10px;
            font-size: 28px;
        }

        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
            line-height: 1.6;
        }

        .section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .section-title {
            color: #333;
            font-size: 18px;
            margin-bottom: 15px;
            font-weight: bold;
        }

        .question {
            margin-bottom: 20px;
        }

        .question-title {
            color: #555;
            margin-bottom: 10px;
            font-weight: 500;
        }

        .required {
            color: red;
        }

        .radio-group, .checkbox-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .radio-group label, .checkbox-group label {
            display: flex;
            align-items: center;
            padding: 10px;
            background: white;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .radio-group label:hover, .checkbox-group label:hover {
            background: #e8eaf6;
            transform: translateX(5px);
        }

        input[type="radio"], input[type="checkbox"] {
            margin-right: 10px;
            cursor: pointer;
            width: 18px;
            height: 18px;
        }

        input[type="text"], textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s;
            font-family: inherit;
        }

        input[type="text"]:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
        }

        textarea {
            min-height: 80px;
            resize: vertical;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            margin-top: 10px;
        }

        th, td {
            padding: 12px;
            text-align: center;
            border: 1px solid #ddd;
        }

        th {
            background: #667eea;
            color: white;
            font-weight: 500;
        }

        .code-block {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 6px;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            overflow-x: auto;
            margin: 10px 0;
            white-space: pre;
        }

        .text-display {
            background: #fff3cd;
            border: 1px solid #ffc107;
            padding: 12px;
            border-radius: 6px;
            margin: 10px 0;
            color: #856404;
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4);
        }

        .submit-btn:active {
            transform: translateY(0);
        }

        .loading {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .error {
            background: #fee;
            border: 2px solid #f44336;
            border-radius: 8px;
            padding: 20px;
            color: #c62828;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="formContainer">
            <div class="loading">
                <h2>加载中...</h2>
                <p>正在获取调查内容</p>
            </div>
        </div>
    </div>

    <script>
        let surveyConfig = null;
        let surveyId = null;

        // 页面加载时执行
        window.onload = function() {
            // 从URL中提取surveyId
            const pathParts = window.location.pathname.split('/');
            surveyId = pathParts[pathParts.length - 1];

            if (!surveyId) {
                showError('无效的调查链接');
                return;
            }

            loadSurvey();
        };

        // 加载调查配置
        function loadSurvey() {
            fetch(`/api/survey/${surveyId}/config`)
                .then(r => r.json())
                .then(config => {
                    surveyConfig = config;
                    renderForm();
                })
                .catch(err => {
                    showError('加载调查失败: ' + err.message);
                });
        }

        // 渲染表单
        function renderForm() {
            let html = `
                <h1>${surveyConfig.title}</h1>
                <p class="subtitle">${surveyConfig.description || ''}</p>
                <form id="surveyForm">
            `;

            surveyConfig.sections.forEach((section, sIndex) => {
                html += `
                    <div class="section">
                        <div class="section-title">${section.title}</div>
                `;

                section.questions.forEach((q, qIndex) => {
                    html += renderQuestion(q, sIndex, qIndex);
                });

                html += '</div>';
            });

            html += `
                    <button type="submit" class="submit-btn">提交调查表</button>
                </form>
            `;

            document.getElementById('formContainer').innerHTML = html;

            // 绑定提交事件
            document.getElementById('surveyForm').addEventListener('submit', handleSubmit);
        }

        // 渲染单个问题
        function renderQuestion(q, sIndex, qIndex) {
            const name = `q_${sIndex}_${qIndex}`;
            const requiredMark = q.required ? ' <span class="required">*</span>' : '';

            let html = '<div class="question">';

            // 特殊题型:代码展示
            if (q.type === 'code_display') {
                html += `
                    <div class="question-title">${q.question}${requiredMark}</div>
                    <div class="code-block">${escapeHtml(q.code || '')}</div>
                `;
                html += '</div>';
                return html;
            }

            // 特殊题型:文本说明
            if (q.type === 'text_display') {
                html += `
                    <div class="text-display">
                        <strong>${q.question}</strong><br>
                        ${q.content || ''}
                    </div>
                `;
                html += '</div>';
                return html;
            }

            // 普通问题
            html += `<div class="question-title">${q.question}${requiredMark}</div>`;

            switch (q.type) {
                case 'text':
                    html += `<input type="text" name="${name}" ${q.required ? 'required' : ''} placeholder="${q.placeholder || ''}">`;
                    break;

                case 'textarea':
                    html += `<textarea name="${name}" ${q.required ? 'required' : ''} placeholder="${q.placeholder || ''}"></textarea>`;
                    break;

                case 'radio':
                    html += '<div class="radio-group">';
                    (q.options || []).forEach((opt, i) => {
                        html += `
                            <label>
                                <input type="radio" name="${name}" value="${escapeHtml(opt)}" ${q.required ? 'required' : ''}>
                                ${escapeHtml(opt)}
                            </label>
                        `;
                    });
                    html += '</div>';
                    break;

                case 'checkbox':
                    html += '<div class="checkbox-group">';
                    (q.options || []).forEach((opt, i) => {
                        html += `
                            <label>
                                <input type="checkbox" name="${name}" value="${escapeHtml(opt)}">
                                ${escapeHtml(opt)}
                            </label>
                        `;
                    });
                    html += '</div>';
                    break;

                case 'table':
                    html += '<table>';
                    html += '<thead><tr><th>知识点</th>';
                    (q.columns || []).forEach(col => {
                        html += `<th>${escapeHtml(col)}</th>`;
                    });
                    html += '</tr></thead><tbody>';

                    (q.rows || []).forEach((row, rIndex) => {
                        const rowName = `${name}_row${rIndex}`;
                        html += `<tr><td>${escapeHtml(row)}</td>`;
                        (q.columns || []).forEach((col, cIndex) => {
                            html += `<td><input type="radio" name="${rowName}" value="${escapeHtml(col)}" ${q.required ? 'required' : ''}></td>`;
                        });
                        html += '</tr>';
                    });

                    html += '</tbody></table>';
                    break;

                default:
                    html += `<p style="color: red;">未知题型: ${q.type}</p>`;
            }

            html += '</div>';
            return html;
        }

        // 处理表单提交
        function handleSubmit(e) {
            e.preventDefault();

            const formData = new FormData(e.target);
            const data = {
                responses: {}
            };

            // 收集所有问题的答案
            surveyConfig.sections.forEach((section, sIndex) => {
                section.questions.forEach((q, qIndex) => {
                    const name = `q_${sIndex}_${qIndex}`;

                    if (q.type === 'code_display' || q.type === 'text_display') {
                        return; // 跳过展示类型
                    }

                    if (q.type === 'checkbox') {
                        data.responses[q.id] = formData.getAll(name);
                    } else if (q.type === 'table') {
                        data.responses[q.id] = {};
                        (q.rows || []).forEach((row, rIndex) => {
                            const rowName = `${name}_row${rIndex}`;
                            data.responses[q.id][row] = formData.get(rowName);
                        });
                    } else {
                        data.responses[q.id] = formData.get(name);
                    }
                });
            });

            // 提取姓名字段
            data.name = data.responses.name || '匿名';

            // 提交到服务器
            fetch(`/api/submit/${surveyId}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            })
            .then(r => r.json())
            .then(result => {
                if (result.success) {
                    alert('✅ 提交成功!感谢你的配合!\n\n老师会根据大家的反馈调整教学方式。');
                    e.target.reset();
                    window.scrollTo(0, 0);
                } else {
                    alert('❌ 提交失败: ' + result.message);
                }
            })
            .catch(err => {
                alert('❌ 提交失败,请检查网络连接或联系老师\n' + err.message);
            });
        }

        function showError(message) {
            document.getElementById('formContainer').innerHTML = `
                <div class="error">
                    <h2>出错了</h2>
                    <p>${message}</p>
                </div>
            `;
        }

        function escapeHtml(unsafe) {
            if (!unsafe) return '';
            return unsafe
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }
    </script>
</body>
</html>
